from flask import Blueprint, jsonify, current_app, request
import json
from pathlib import Path

from app.services.device_report import get_device_reporter

# 创建蓝图
device_bp = Blueprint('device', __name__)

@device_bp.route('/current-school', methods=['GET'])
def get_current_school():
    """获取当前绑定的学校名称"""
    try:
        # 从保存的配置文件中读取当前学校名称
        config_dir = Path('/home/mobox/mobox_dashboard/config')
        school_config_file = config_dir / "current_school.json"
        
        if school_config_file.exists():
            with open(school_config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                school_name = config.get('school_name')
                if school_name:
                    return jsonify({
                        'code': 0,
                        'message': '获取成功',
                        'data': {
                            'school_name': school_name,
                            'updated_at': config.get('updated_at')
                        }
                    })
        
        # 如果没有保存的配置文件，返回默认值
        return jsonify({
            'code': 0,
            'message': '使用默认学校',
            'data': {
                'school_name': '测试学校',
                'updated_at': None
            }
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'获取当前学校失败: {str(e)}',
            'data': None
        }), 500

@device_bp.route('/report', methods=['POST'])
def report_device_status():
    """手动上报设备状态"""
    try:
        reporter = get_device_reporter()
        if reporter:
            result = reporter.report_status()
            if result:
                return jsonify({'status': 'success', 'message': '设备状态上报成功'})
            else:
                return jsonify({'status': 'error', 'message': '设备状态上报失败'}), 500
        else:
            return jsonify({'status': 'error', 'message': '设备上报服务未初始化'}), 500
    except Exception as e:
        return jsonify({'status': 'error', 'message': f'上报失败: {str(e)}'}), 500

@device_bp.route('/last-report', methods=['GET'])
def get_last_report_time():
    """获取最近一次上报时间"""
    reporter = get_device_reporter()
    if reporter and reporter.last_report_time:
        return jsonify({'status': 'success', 'last_report_time': reporter.last_report_time.isoformat()})
    else:
        return jsonify({'status': 'error', 'message': '尚未上报'}), 404

@device_bp.route('/logs', methods=['GET'])
def get_device_logs():
    """获取设备上报相关日志"""
    import subprocess
    
    try:
        # 从系统日志中获取设备上报相关的日志 - 使用更简单的grep模式
        log_cmd = "journalctl -u mobox-dashboard --lines=200 --no-pager | grep '设备' | tail -50"
        result = subprocess.run(log_cmd, shell=True, capture_output=True, text=True)
        
        if result.returncode == 0:
            log_lines = result.stdout.strip().split('\n') if result.stdout.strip() else []
            # 过滤掉空行
            log_lines = [line for line in log_lines if line.strip()]
            return jsonify({
                'status': 'success', 
                'logs': log_lines,
                'count': len(log_lines)
            })
        else:
            # 如果grep没找到匹配项，返回空列表而不是错误
            return jsonify({
                'status': 'success', 
                'logs': [],
                'count': 0
            })
            
    except Exception as e:
        return jsonify({'status': 'error', 'message': f'获取日志失败: {str(e)}'}), 500 